from re import T
import sys
import argparse
from tkinter.messagebox import NO
from ui_main import Ui_MainWindow
import ui_window1
import cv2
import yaml
from PySide6.QtGui import QImage, QPixmap, QCursor, QMouseEvent
from PySide6.QtWidgets import QApplication, QMainWindow, QWidget
from PySide6.QtCore import Qt, QTimer, Signal, QPoint, QRect
from motion_detector import MotionDetector
from my_widget import hint
from coordinates_generator import CoordinatesGenerator
from colors import *

def parse_args():
    parser = argparse.ArgumentParser(description='Generates Coordinates File')

    parser.add_argument("--image",
                        dest="image_file",
                        required=False,
                        help="Image file to generate coordinates on")

    parser.add_argument("--video",
                        dest="video_file",
                        required=True,
                        help="Video file to detect motion on")

    parser.add_argument("--data",
                        dest="data_file",
                        required=True,
                        help="Data file to be used with OpenCV")
    return parser.parse_args()

class my_MainWindow(Ui_MainWindow):
    def __init__(self, MainWindow, img=0, video=0, coordinates=0):
        # self.all_show = [self.park_avail, self.revenue, self.park_state, self.against, self.white_list]
        # if img is not None:
        #     with open(coordinates, "w+") as points:
        #         # 手动生成停车场底图
        #         generator = CoordinatesGenerator(img, points, COLOR_RED)
        #         generator.generate()
        # with open(coordinates, "w+") as data:
        #     # 初始化界面
        #     self.setupUi(MainWindow)
        #     for i in self.all_show:
        #         i.setVisible(False)
        #     MainWindow.setWindowFlags(Qt.FramelessWindowHint)
        #     MainWindow.setAttribute(Qt.WA_TranslucentBackground)
            # self.points = yaml.load(data)
            # self.det_thread = MotionDetector(video, points)
            # self.det_thread.send_raw.connect(lambda x: self.show_park_img(x))
            # self.det_thread.send_img.connect(lambda x: self.transform(x))
            
        #     self.Left_list.Mywig3.cwzt.clicked.connect(self.show(self.park_state))
        # self.park_avail.setStyleSheet()
        
        self.setupUi(MainWindow)
        self.pushButton.setCursor(QCursor(Qt.PointingHandCursor))
        self.avail = None
        self.park_state.setVisible(False)
        self.park_state_v = False
        self.park_avail_v = False
        self.park_avail.setVisible(False)
        self.Left_list.Mywig3.cwzt.clicked.connect(self.show_park_stage)
        self.Left_list.Mywig1_s.but1.clicked.connect(self.show_park_avail)
        
        self.park_avail.setStyleSheet(u"background-color: white;\n")
        self.park_avail.possig.connect(lambda x: self.show_park_avail_hint(x))
        # self.park_state.comboBox.currentIndexChanged.connect(self.switch_park_view)
        
        # MainWindow.setWindowFlags(Qt.FramelessWindowHint)
        # MainWindow.setAttribute(Qt.WA_TranslucentBackground)
        
    
    # 显示浮动窗口信息
    def show_park_avail_hint(self, pos):
        # 实例化一个窗口
        # 如果已经有窗口需要先清空该窗口
        if self.avail is not None:
            self.avail.deleteLater()
            x, y = pos.x(), pos.y()
            self.avail = hint(self.park_avail)
            # self.avail.label1.setText(f"发布车位数: {len(self.det_thread.coordinates_data)}")
            # self.avail.label2.setText(f"使用车位数: {self.det_thread.count}")
            # self.avail.label3.setText(f"空闲车位数: {len(self.det_thread.coordinates_data) - self.det_thread.count}")
            self.avail.setGeometry(QRect(x, y, 150, 100))
            self.avail.setVisible(True)
            self.avail.but.clicked.connect(self.show_park_stage)
        else:
            x, y = pos.x(), pos.y()
            self.avail = hint(self.park_avail)
            # self.avail.label1.setText(f"发布车位数: {len(self.det_thread.coordinates_data)}")
            # self.avail.label2.setText(f"使用车位数: {self.det_thread.count}")
            # self.avail.label3.setText(f"空闲车位数: {len(self.det_thread.coordinates_data) - self.det_thread.count}")
            self.avail.setGeometry(QRect(x, y, 150, 100))
            self.avail.setVisible(True)
            self.avail.but.clicked.connect(self.show_park_stage)

    
    # 显示车位状态
    def show_park_stage(self):
        if not self.park_state_v and self.park_avail_v:
            self.park_state_v = True
            self.park_avail_v = False
            self.park_avail.setVisible(self.park_avail_v)
            self.park_state.setVisible(self.park_state_v)
            self.park_state.fabu.setText(f"发布车位数: {len(self.det_thread.coordinates_data)}")
            self.park_state.shiyong.setText(f"使用车位数: {self.det_thread.count}")
            self.park_state.kongxian.setText(f"空闲车位数: {len(self.det_thread.coordinates_data) - self.det_thread.count}")
        else:
            self.park_state_v = True
            self.park_state.setVisible(self.park_state_v)
        
        
    # 显示车位信息
    def show_park_avail(self):
        if not self.park_avail_v and self.park_state_v:
            self.park_state_v = False
            self.park_avail_v = True
            self.park_avail.setVisible(self.park_avail_v)
            self.park_state.setVisible(self.park_state_v)
        else:
            self.park_avail_v = True
            self.park_avail.setVisible(self.park_avail_v)
        
    # 更改摄像机
    def switch_park_view(self):
        try:
            if self.park_state.comboBox.currentIndex() == 1:
                self.det_thread = MotionDetector(0, self.points)
        except Exception as e:
            pass
    
    # 展示车位状态
    def show_park_img(self, img):
        img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
        img = cv2.resize(img, (800, 490))
        # 转化为Qt形式数据进行展示
        qt_img = QImage(img.data, img.shape[1], img.shape[0], img.shape[1] * 3, QImage.Format_RGB888)
        qt_img = QPixmap.fromImage(qt_img)
        self.park_state.park_show.setPixmap(qt_img)
        
    # 将将车位状态转换为全景信息底图
    def transform(self, img):
        close = False
        coordinates = []
        trans_coor = []
        cv2.namedWindow("image")
        img = cv2.imread(img)
        cv2.setMouseCallback("image", __mouse_callback)
        # trans = np.zeros((800, 490), dtype=np.uint8)
        trans_point = [(0, 0), (800, 0), (800, 490), (0, 490)]
        while True:
            if not close:
                cv2.imshow("image", img)
                cv2.waitKey(0)
            else:
                break  
        M = cv2.getPerspectiveTransform(coordinates, trans_point)
        trans = cv2.warpPerspective(img, M, [800, 490])
        for index, point in enumerate(self.coordinates_data):
            # 将转换后的车位坐标记录并记录是否有停车
            trans_coor.append(M * self._coordinates(point))
            # 如果车位已经占用显示红色,否则显示绿色
            if self.det_thread.statuses[index]:
                trans = cv2.polylines(trans, [M * self._coordinates(point)], isClosed=True, color=COLOR_RED, thickness=1)
                trans = cv2.fillPoly(trans, [M * self._coordinates(point)], color=COLOR_RED)
            else:
                trans = cv2.polylines(trans, [M * self._coordinates(point)], isClosed=True, color=COLOR_GREEN, thickness=1)
                trans = cv2.fillPoly(trans, [M * self._coordinates(point)], color=COLOR_GREEN)
        qt_img = QImage(trans.data, trans.shape[1], trans.shape[0], trans.shape[1] * 3, QImage.Format_RGB888)
        qt_img = QPixmap.fromImage(qt_img)
        self.park_avail.setPixmap(qt_img)
        
        def __mouse_callback(event, x, y, flags, params):
            count = 0
            if event == cv2.EVENT_LBUTTONDOWN:
                coordinates.append((x, y))
                count += 1
            # 排序坐标点
            if count == 4:
                # 关闭窗口计算变换矩阵
                cv2.destroyAllWindows()
                close = True
                
                

    # 可用停车位
    # def get_avail(self):
    #     self.transform()
    # # 跨日停车
    # def get_time(self):
    #     for t in self.times:
            
    # # 财务营收
    # def get_revenue(self):
        
    # def show(self, label):
    #     # 同一时间只展示一个状态栏
    #     for i in self.all_show:
    #         if i == label:
    #             i.setVisable(True)
    #         i.setVisable(False)
    
    def mouseMoveEvent(self, event: QMouseEvent) -> None:
        self._endPos = event.pos() - self._startPos
        self.move(self.pos() + self._endPos)
        
    def mousePressEvent(self, event: QMouseEvent) -> None:
        if event.button() == Qt.LeftButton:
            self._isTracking = True
            self._startPos = QPoint(event.x(), event.y())
            
    def mouseReleaseEvent(self, event: QMouseEvent) -> None:
        if event.button() == Qt.LeftButton:
            self._isTracking = False
            self._startPos = None
            self._endPos = None
        
        
    
def main():
    # args = parse_args()
    app = QApplication(sys.argv)
    w = QMainWindow()
    
    # win1 = ui_window1.Ui_Form()
    # win1.setupUi(w)
    # main_window = my_MainWindow(w, args.image, args.video, args.data)
    main_window = my_MainWindow(w)
    w.show()
    
    sys.exit(app.exec())
    

if __name__ == '__main__':
    main()
